//
//  HLTHomeViewController.m
//  huiliantong
//
//  Created by hlt on 15/8/11.
//  Copyright (c) 2015年 hlt. All rights reserved.
//

#import "HLTHomeViewController.h"
#import "HomeMenuCell.h"
#import "HLadvsTableViewCell.h"
#import "RecommendCell.h"
#import "HLTShopViewController.h"
#import "SearchViewController.h"
#import "cloudsearchmapViewController.h"
#import "HLTzoubianTableViewController.h"
@interface HLTHomeViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    NSMutableArray *_menuArray;//菜单按钮
    NSMutableArray *_rushArray;//抢购数据
//    HotQueueModel *_hotQueueData; //
    NSMutableArray *_recommendArray;
    NSMutableArray *_discountArray;
    
     NSArray *imagearray;    //滚动广告数据
    
}





@property (strong, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation HLTHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    //取消分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    [self initData];
    [self setNav];
    [self initTableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//初始化数据
-(void)initData{
//    _rushArray = [[NSMutableArray alloc] init];
////    _hotQueueData = [[HotQueueModel alloc] init];
    _recommendArray = [[NSMutableArray alloc] init];   //商铺数据
//    _discountArray = [[NSMutableArray alloc] init];
//
    
    //获取滚动广告的方法
//    [self getadvs];
    //获取推荐商铺列表
    [self getrecommendlist];
    
    
    //首页的功能分类列表
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"menuData" ofType:@"plist"];
    _menuArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    
//    [self getmenuarray];
}

//-(void) getmenuarray
//{
//    
//    NSString *url=@"http://www.hltgz.com/wx/mobile/index.php?m=default&c=appinterface&a=category";
//    [HLTNetWorkingtool getyouhuilist:url success:^(NSMutableArray *ary) {
//        
////        NSArray *aaary=ary;
//        
//        
//        
//        
//    } faliure:^(NSString *error) {
//       
//    }];
//
//    
//}





//获取推荐商铺列表
-(void) getrecommendlist
{
    NSString *url=@"http://www.hltgz.com/wx/mobile/index.php?m=default&c=appinterface&a=recommend&page=0";
    [HLTNetWorkingtool getyouhuilist:url success:^(NSMutableArray *ary) {
        
        [_recommendArray removeAllObjects];
        for (int i = 0; i < ary.count; i++) {
            RecommendModel *recommend = [RecommendModel objectWithKeyValues:ary[i]];
            [_recommendArray addObject:recommend];
        }
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        //刷新指定的section,显示推荐商铺的部分
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        
        
        imagearray=_recommendArray;
        //刷新指定的section,显示滚动广告的部分
        NSIndexSet *indexSet1=[[NSIndexSet alloc]initWithIndex:0];
        [self.tableView reloadSections:indexSet1 withRowAnimation:UITableViewRowAnimationAutomatic];
        
 
    } faliure:^(NSString *error) {
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    }];
    
    
    
    
    
}






//获取滚动广告
//-(void) getadvs
//{
//    
//    
//    NSString *url=recommendlist;
//    [HLTNetWorkingtool getary:url success:^(NSArray *ary) {
//        NSMutableArray *maary=[[NSMutableArray alloc]initWithCapacity:10];
//        for (int i = 0; i < ary.count; i++) {
//            RecommendModel *recommend = [RecommendModel objectWithKeyValues:ary[i]];
//            [maary addObject:recommend];
//        }
//
//        imagearray=maary;
//        //刷新指定的section,显示滚动广告的部分
//        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
//        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
//
//        
//        
//    } faliure:^(NSString *error) {
//        
//    }];
//    
//    
//}






//设置导航栏的几个控件
-(void)setNav{
    
    
    //设置导航的标题的字体大小和颜色
    [self.navigationController.navigationBar setTitleTextAttributes:
     
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screen_width, 64)];
    backView.backgroundColor = navigationBarColor;
    [self.view addSubview:backView];
    //城市
    UIButton *cityBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cityBtn.frame = CGRectMake(10, 30, 40, 25);
    cityBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [cityBtn setTitle:@"贵阳" forState:UIControlStateNormal];
    [backView addSubview:cityBtn];
    //城市旁边向下的箭头
//    UIImageView *arrowImage = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(cityBtn.frame), 38, 13, 10)];
//    [arrowImage setImage:[UIImage imageNamed:@"icon_homepage_downArrow"]];
//    [backView addSubview:arrowImage];
    //地图
    UIButton *mapBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [mapBtn addTarget:self action:@selector(openmap) forControlEvents:UIControlEventTouchDown];
    mapBtn.frame = CGRectMake(screen_width-42, 30, 42, 30);
    [mapBtn setImage:[UIImage imageNamed:@"icon_homepage_map_old"] forState:UIControlStateNormal];
    //覅安吉地图进入附近的界面
//    [mapBtn addTarget:self action:@selector(OnMapBtnTap:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:mapBtn];
    
    //搜索框的背景
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(cityBtn.frame)+10, 30, screen_width-120, 25)];
    //    searchView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background_home_searchBar"]];
    searchView.backgroundColor = RGB(0, 176, 252);
    searchView.layer.masksToBounds = YES;
    searchView.layer.cornerRadius = 12;   //设置圆角
    [backView addSubview:searchView];
    
    //小搜索图片
    UIImageView *searchImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 3, 15, 15)];
    [searchImage setImage:[UIImage imageNamed:@"icon_homepage_search"]];
    [searchView addSubview:searchImage];
    
    UILabel *placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 0, 150, 25)];
    placeHolderLabel.font = [UIFont boldSystemFontOfSize:13];
    placeHolderLabel.text = @"请输入搜索关键字";
    //    placeHolderLabel.text = @"鲁总专享版";
    placeHolderLabel.textColor = [UIColor whiteColor];
    [searchView addSubview:placeHolderLabel];
    
    UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(seach)];
    
    [searchView addGestureRecognizer:tapGesturRecognizer];
    
    
    
}







-(void) openmap
{
    
//    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    
//    cloudsearchmapViewController * map = [story instantiateViewControllerWithIdentifier:@"zoubianmap"];
//    //    shoplist.hidesBottomBarWhenPushed = YES;

    
    HLTzoubianTableViewController *vc=[[HLTzoubianTableViewController alloc]init];
    
    vc.shoptye=zoubian;
    vc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:vc animated:NO];
    
}




-(void) seach
{
//     SearchViewController   *vc=[[SearchViewController alloc]init];
//     vc.sourceType = SearchBarTypeHome;
////    vc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:vc animated:YES];
    
    
    SearchViewController *search1= [[SearchViewController alloc] init];
    search1.sourceType = SearchBarTypeHome;
    [self.navigationController pushViewController:search1 animated:NO];
    
    
    
}


//设置tabviewde 初始化位置和委托
-(void)initTableView{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, screen_width,screen_height-49-64) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    //使分割线不向右偏移的方法
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
    
    //设置下拉刷新的内容
    [self setUpTableView];
    
    //去掉多余分割线的方法
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [self.tableView setTableFooterView:view];
    
    
}

-(void)setUpTableView{
    //添加下拉的动画图片
    //设置下拉刷新回调
    [self.tableView addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    
//    //设置普通状态的动画图片
//    NSMutableArray *idleImages = [NSMutableArray array];
//    for (NSUInteger i = 1; i<=60; ++i) {
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_anim__000%zd",i]];
//        [idleImages addObject:image];
//    }
////    [self.tableView.gifHeader setImages:idleImages forState:MJRefreshHeaderStateIdle];
//    
//    //设置即将刷新状态的动画图片
////    NSMutableArray *refreshingImages = [NSMutableArray array];
//    for (NSInteger i = 1; i<=3; i++) {
//        
//        NSString *str=[NSString stringWithFormat:@"dropdown_loading_0%zd",i];
//        
//        
//        UIImage *image1 = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_loading_0%zd",i]];
////        [refreshingImages addObject:image1];
//    }
////    [self.tableView.gifHeader setImages:refreshingImages forState:MJRefreshHeaderStatePulling];
//    
//    //设置正在刷新是的动画图片
////    [self.tableView.gifHeader setImages:idleImages forState:MJRefreshHeaderStateRefreshing];
//    
    //马上进入刷新状态
    [self.tableView.gifHeader beginRefreshing];
}

//调用高德地图的接口
-(void)OnMapBtnTap:(UIButton *)sender{
//    JZMapViewControlle *JZMapVC = [[JZMapViewControlle alloc] init];
//    [self.navigationController pushViewController:JZMapVC animated:YES];
}


//下拉刷新的回调函数
-(void)refreshData{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
        //刷新后需要加载的数据
        [self getrecommendlist];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //update UI
        });
    });
}



#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //    if (_rushArray.count == 0) {
    //        return 2;
    //    }else{
    //        return 3;
    //    }
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 2) {
        return _recommendArray.count+1;
    }else
    {
    return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSUInteger section = [indexPath section];
    if (0 == section) {
        CGFloat aa=screen_width/1.5;
        return   aa;
        
    }else if(indexPath.section == 2)
    {
                if (indexPath.row == 0) {
                    return 35.0;
                }else{
                    return 90.0;
                }
    }
    else
    {
        return 180;
        
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return 5;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screen_width, 10)];
    headerView.backgroundColor = RGB(239, 239, 244);
    //    headerView.backgroundColor = [UIColor redColor];
    return headerView;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screen_width, 0)];
    footerView.backgroundColor = RGB(239, 239, 244);
    //    footerView.backgroundColor = [UIColor yellowColor];
    return footerView;
}



- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
}









-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *cscell=@"cscell";
        static NSString *HLadvsTableViewCell1 = @"HLadvsTableViewCell";
        UITableViewCell *cellcs = [ tableView dequeueReusableCellWithIdentifier: cscell ];
        if (cellcs==nil) {
            cellcs = [ [ UITableViewCell alloc ] initWithFrame: CGRectZero reuseIdentifier: cscell];
        }
        
//                NSString *shopImage = @"http://img0.bdstatic.com/img/image/ziranfengguang1.jpg,http://www.xinglico.com/uploadfiles/Pictures/bianji/2015_04/GXJ/20150427162824_3558.jpg,http://www.xinglico.com/uploadfiles/Pictures/bianji/2015_04/GXJ/20150427162824_6218.jpg,http://www.xinglico.com/uploadfiles/Pictures/bianji/2015_04/GXJ/20150427162824_4130.jpg,";
//        
//                NSMutableArray *mary=[[NSMutableArray alloc] initWithCapacity:1];
//                for (NSDictionary  *str in imagearray) {
//        
//                    NSString *str1= [NSString stringWithFormat:@"%@%@",xhturl,str[@"imgUrl"]];
//                    [mary addObject:str1];
//                }
//                NSArray *shopimagearray;// = [shopImage componentsSeparatedByString:@","]; //从字符A中分隔成2个元素的数组
//                if ([mary count]>0) {
//        
//                    shopimagearray=mary;
//                }
        
         NSArray *shopimagearray;
        if ([imagearray count]>0) {
            
            shopimagearray=imagearray;
        }
        
        HLadvsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HLadvsTableViewCell1];
        if(cell == nil)
        {
            
            if ([shopimagearray count]>1) {
                cell= [[[NSBundle mainBundle]loadNibNamed:@"HLadvsTableViewCell" owner:nil options:nil] firstObject];
            }
            else
            {
                return cellcs;
            }
        }
        cell.parent=self;
        cell.backgroundColor=[UIColor clearColor];//关键语句
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        cell.imagearray=shopimagearray;
        if ([shopimagearray count]>0) {
            [cell start];
        }
        return cell;
        

        
     }
    else if (indexPath.section == 1)
    {
        
        
        static NSString *cellIndentifier = @"menucell";
        HomeMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[HomeMenuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier menuArray:_menuArray];
        }
        
//        cell.backgroundColor=RGB(240, 255, 255);
        
        cell.parent=self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

        
        
    }
    else{//推荐
        if(indexPath.row == 0){
            static NSString *cellIndentifier = @"morecell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
            }
            
            cell.textLabel.text = @"猜你喜欢";
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }else{
            static NSString *cellIndentifier = @"recommendcell";
            RecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
            if (cell == nil) {
                cell = [[RecommendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
            }
            
            if(_recommendArray.count!=0){
                RecommendModel *recommend = _recommendArray[indexPath.row-1];
                [cell setRecommendData:recommend];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }
        
    }
}



#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 2){
                if (indexPath.row !=0) {
                    RecommendModel *recommend = _recommendArray[indexPath.row-1];

                    HLTShopViewController *shopvc=[[HLTShopViewController alloc]init];
                    shopvc.biaozhi=YES;
                    shopvc.shopcontent=recommend;
                    shopvc.hidesBottomBarWhenPushed = YES;
                     [self.navigationController pushViewController:shopvc animated:YES];

                }
            }

    }


//将要出现的时候
- (void)viewWillAppear:(BOOL)animated
{
    //隐藏导航
    self.navigationController.navigationBarHidden=YES;
    
}


//将要消失的时候
- (void)viewWillDisappear:(BOOL)animated
{
    //打开导航
    self.navigationController.navigationBarHidden=NO;
    
}







/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
